var QQMapWX = require("../../libs/qqmap-wx-jssdk.js");
var qqmapsdk;
const util = require('../../utils/util.js');
const app = getApp();
var leaveMsg = {};
qqmapsdk = new QQMapWX({
    key: 'FS4BZ-HINKW-7XBRR-OLZ5Y-PLPF6-5CF5J'
});
Page({
    /**
     * 页面的初始数据
     */
    data: {
        showModalStatus: false,
        address_id: '',
        payment: ['在线支付', '货到付款'],
        paymentIndex: 0,
        arrivalObj: {},
        pay_name: 'online',
        leaveMsg: '',
        ifcart: '',
        showModalStatus1: false,
        showModalStatusStore: false,
        rcbState: false,
        pdState: false,
        disableRcb: false,
        disablePd: false,
        showRercb: false,
        showRepd: false,
        showPswtip: false,
        wechatpaySelected: true,
        rcb_pay: 0,
        pd_pay: 0,
        rptIndex: '',
        voucherIndex: 0,
        rpt: '',
        voucher: '',
        storeVoucher: {},
        arrtimeObj: {},
        showConfirmPay: true,
        openid: '',
        curType: 0,
        storeChainInfo: [],
        username: '',
        chain_member_phone: '',
        inDeliveryScope: true,
        allImageUrl: app.globalData.imageUrl
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
        var self = this;

        if (app.globalData.openid) {
            this.setData({
                openid: app.globalData.openid
            })
        } else {
            wx.login({
                success: res => {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=connect&op=wechat_jscode',
                        data: {
                            js_code: res.code
                        },
                        method: 'GET',
                        dataType: 'json',
                        success: (res) => {
                            this.setData({
                                openid: res.data.datas.openid
                            })
                        },
                    });
                }
            });
        }
        if (options.newAddress_id) {
            this.setData({
                address_id: options.newAddress_id
            })
        }
        util.share();
        wx.getStorage({
            key: 'key',
            success: res => {
                self.setData({
                    key: res.data
                })
            }
        })
        wx.getStorage({
            key: 'username',
            success: res => {
                self.setData({
                    username: res.data
                })
            }
        })
        wx.getStorage({
            key: 'member_mobile',
            success: res => {
                self.setData({
                    chain_member_phone: res.data
                })
            }
        })
        if (options.address_id) {
            this.setData({
                address_id: options.address_id
            })
        }
        if (options.ifcart == 1) {
            this.setData({
                cart_id: options.cart_id.toString(),
                ifcart: 1
            })
        } else {
            this.setData({
                cart_id: options.goods_id + '|' + options.buynum
            })
        }
    },
    onShow: function () {
        if (this.data.key) {
            if (this.data.address_api == "") {
                this.onReady();
            }
        }

        this.setData({
            totalPriceTmpl: this.data.inittotalPrice
        })
        if (this.data.voucherIndex != 0 && this.data.rptIndex == '') {
            for (let key in this.data.storeVoucher) {
                this.data.totalPriceTmpl -= this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_price
            }
            this.setData({
                totalPrice: this.data.totalPriceTmpl.toFixed(2)
            })
        }
        if (this.data.voucherIndex == 0 && this.data.rptIndex != '') {
            this.setData({
                totalPrice: (this.data.totalPriceTmpl * 1 - this.data.rpt_list[this.data.rptIndex].rpacket_price).toFixed(2)
            })
        }
        if (this.data.voucherIndex != 0 && this.data.rptIndex != '') {
            for (let key in this.data.storeVoucher) {
                this.data.totalPriceTmpl -= this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_price
            }
            this.setData({
                totalPrice: (this.data.totalPriceTmpl * 1 - this.data.rpt_list[this.data.rptIndex].rpacket_price).toFixed(2)
            })
        }

        if (JSON.stringify(this.data.address_info) == "{}") {
            wx.showModal({
                title: '温馨提示',
                content: '请添加收货人信息',
                success: res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../address_choose/address_choose?iforder=1'
                        })
                    } else if (res.cancel) {
                        wx.navigateBack({
                            delta: 1
                        })
                    }
                }
            })
        }
    },
    choosePay: function (e) {
        var self = this;
        if (e.detail.value == 0) {
            this.setData({
                pay_name: 'online'
            })
        }
        if (e.detail.value == 1) {
            wx.request({
                url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=offline_check',
                method: 'POST',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                    key: self.data.key
                },
                dataType: 'json',
                success: (res) => {
                    wx.showToast({
                        title: '不满足货到付款条件',
                        icon: 'none'
                    })
                }
            })
        }
    },
    chooseArrDay: function (e) {
        var storeId = e.currentTarget.dataset.store_id;
        var value = e.currentTarget.dataset.time_value;
        var logistics_final_start_time = e.currentTarget.dataset.logistics_final_start_time;
        var logistics_final_end_time = e.currentTarget.dataset.logistics_final_end_time;
        var arr_data_value = e.currentTarget.dataset.arr_data_value;
        this.setData({
            value: value,
            store_id: storeId,
            arr_data_value: arr_data_value
        })
        //选择配送时间
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=arrival_time',
            data: {
                key: self.data.key,
                value: self.data.value,
                store_id: self.data.currstoreId,
                logistics_final_start_time: logistics_final_start_time,
                logistics_final_end_time: logistics_final_end_time
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
                self.setData({
                    defaultAm_time: res.data.datas.am_time
                })
            }
        })
    },
    chooseArrtime: function (e) {
        var arrival = '';
        var arrivalTime = this.data.arrivalObj;
        var arr_time_value = e.currentTarget.dataset.arr_time_value;
        var arrival_time = e.currentTarget.dataset.arrival_time;
        var arrival_start = parseInt(this.data.value) + parseInt(arrival_time.split('-')[0]);
        var arrival_end = parseInt(this.data.value) + parseInt(arrival_time.split('-')[1]);
        var storeId = e.currentTarget.dataset.store_id;
        var arr_time_text = this.data.arr_data_value + arr_time_value
        arrivalTime['store_id' + storeId] = arrival_start + '-' + arrival_end
        for (var i in arrivalTime) {
            arrival += i + '|' + arrivalTime[i] + ','
        }
        this.data.arrtimeObj[storeId] = {
            arr_time_text: arr_time_text
        }
        this.setData({
            arrival: arrival,
            arrivalObj: arrivalTime,
            showModalStatus: false,
            arrtimeObj: this.data.arrtimeObj
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=buy_step1',
            data: {
                key: self.data.key,
                cart_id: self.data.cart_id,
                ifcart: self.data.ifcart,
                address_id: self.data.address_id,
                pintuan: '',
                ifchain: '',
                chain_id: ''
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            dataType: 'json',
            success: (res) => {
                if (res.data.code == 200) {
                    for (let k in res.data.datas.store_cart_list) {
                        if (res.data.datas.store_cart_list[k].store_voucher_list.length > 0) {
                            self.data.storeVoucher[k] = 0
                        }
                    }
                    self.setData({
                        address_info: res.data.datas.address_info,
                        store_cart_list: res.data.datas.store_cart_list,
                        address_id: res.data.datas.address_info.address_id,
                        vat_hash: res.data.datas.vat_hash,
                        address_api: res.data.datas.address_api,
                        invoice_cont: res.data.datas.inv_info.content,
                        rpt_list: res.data.datas.rpt_list,
                        storeVoucher: self.data.storeVoucher,
                        storeChainInfo: res.data.datas.store_chain_list
                    })
                    wx.getStorage({
                        key: 'latitude',
                        success: res => {
                            let latitude = res.data
                            wx.getStorage({
                                key: 'longitude',
                                success: resl => {
                                    let longitude = resl.data;
                                    var locationArray = [];
                                    for (let i = 0; i < self.data.storeChainInfo.length; i++) {
                                        locationArray[i] = self.data.storeChainInfo[i].location
                                    }

                                    //获取距离店铺位置
                                    qqmapsdk.calculateDistance({
                                        mode: 'walking',
                                        from: {
                                            latitude: latitude,
                                            longitude: longitude
                                        },
                                        to: locationArray,
                                        success: ressuc => {
                                            console.log(ressuc);
                                            if (ressuc.result.elements.length == 1) {
                                                self.setData({
                                                    storeDistanceMinIndex: 0
                                                })
                                            } else {
                                                let minDistance = Math.min.apply(Math, ressuc.result.elements.map(item => {
                                                    return item.distance;
                                                }))
                                                for (let i = 0; i < ressuc.result.elements.length; i++) {
                                                    if (ressuc.result.elements[i].distance == minDistance) {
                                                        self.setData({
                                                            storeDistanceMinIndex: i
                                                        })
                                                    }
                                                }
                                            }
                                            self.setData({
                                                storeDistance: ressuc.result.elements
                                            })
                                        }
                                    })
                                }
                            })
                        }
                    })
                    if (JSON.stringify(res.data.datas.address_info) == "{}") {
                        wx.showModal({
                            title: '温馨提示',
                            content: '请添加收货人信息',
                            success: res => {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '../address_choose/address_choose?iforder=1'
                                    })
                                } else if (res.cancel) {
                                    wx.switchTab({
                                        url: '../cart/cart'
                                    })
                                }
                            }
                        })
                    }
                    if (res.data.datas.inv_info.content == '不需要发票') {
                        self.setData({
                            invoice_id: 0,
                        })
                    } else {
                        self.setData({
                            invoice_id: res.data.datas.inv_info.inv_id
                        })
                    }
                    var arrival = '';
                    var arrivalTime = {};
                    for (var i in res.data.datas.store_cart_list) {
                        arrivalTime['store_id' + i] = res.data.datas.store_cart_list[i].max_time_reach;
                        arrival += 'store_id' + i + '|' + res.data.datas.store_cart_list[i].max_time_reach + ',';
                    }
                    self.setData({
                        arrivalObj: arrivalTime,
                        arrival: arrival
                    })
                    this.getParam(res.data.datas.address_api)
                } else {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none',
                        success: () => {
                            setTimeout(function () {
                                wx.switchTab({
                                    url: '../cart/cart'
                                })
                            }, 1500)
                        }
                    })

                }
            }
        });
    },
    bottomUp: function (e) {
        var currentStatu = e.currentTarget.dataset.statu;
        var storeId = e.currentTarget.dataset.store_id;
        this.util(currentStatu, storeId);
        if (currentStatu == 'open') {
            this.chooseArrDay(e);
        }
    },
    storeAddrUp: function (e) {
        var currentStatu = e.currentTarget.dataset.statu;
        this.utilStore(currentStatu)
    },
    utilStore: function (currentStatu) {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear',
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(100).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatusStore: false
                });
            }
        }.bind(this), 200)
        if (currentStatu == "open") {
            this.setData({
                showModalStatusStore: true
            });
        }
    },
    util: function (currentStatu, storeId) {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear',
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(100).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatus: false,
                    currstoreId: storeId
                });
            }
        }.bind(this), 200)
        if (currentStatu == "open") {
            this.setData({
                showModalStatus: true,
                currstoreId: storeId
            });
        }
    },
    verifyDistance: function () {
        var self = this;
        qqmapsdk.calculateDistance({
            mode: 'straight',
            from: {
                latitude: self.data.address_info.lat,
                longitude: self.data.address_info.lng
            },
            to: [{
                latitude: self.data.address_info.logistics.logistics_reference_lat,
                longitude: self.data.address_info.logistics.logistics_reference_lng
            }],
            success: ressuc => {
                if (ressuc.result.elements[0].distance - self.data.address_info.logistics.logistics_distance * 1000 > 0) {
                    self.setData({
                        inDeliveryScope: false
                    })
                } else {
                    self.setData({
                        inDeliveryScope: true
                    })
                }
            }
        })
    },
    buyStep2: function () {
        var self = this;
        self.verifyDistance()
        if (!this.data.inDeliveryScope) {
            wx.showModal({
                title: '超出配送范围！',
                content: '是否查看可配送范围',
                success: res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../delivery_area/delivery_area'
                        });
                    }
                }
            });
            return false;
        }
        // var arrival_str = self.data.arrival;
        // arrival_str = arrival_str.substring(0, arrival_str.length - 1);
        // var arrival_arr = arrival_str.split(",");
        // let endTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
        // endTime = Date.parse(endTime) / 1000;
        // var arrival_confirm = false;
        // var arrival_tip_time = '';
        // for (var a in arrival_arr) {
        //     var arrival_time = arrival_arr[a].split("|");
        //     if (arrival_time[1].indexOf("-") == -1 && arrival_time[1] > endTime) {
        //         arrival_confirm = true;
        //         var cal_time = (arrival_time[1] - endTime) / 24 / 3600
        //         arrival_tip_time=parseInt(cal_time)+'天后'
        //     }
        // }
        // if (arrival_confirm) {
        //     wx.showModal({
        //         title: '',
        //         content: '您有订单将于' + arrival_tip_time + '配送，\r\n请确认配送时间后继续支付',
        //         showCancel: false,
        //         success(res) {
        //             if (res.confirm) {
        //                 arrival_confirm = false;
        //             }
        //         }
        //     })
        // }
        if (this.data.rptIndex != '') {
            this.data.rpt = this.data.rpt_list[this.data.rptIndex].rpacket_id + '|' + this.data.rpt_list[this.data.rptIndex].rpacket_price
        }
        if (this.data.voucherIndex != '') {
            this.data.voucher = ''
            for (let key in this.data.storeVoucher) {
                if (this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].limit != 0) {
                    this.data.voucher += (this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_t_id + '|' + key + '|' + this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_price) + ','
                }
            }
        }
        var chain = ''
        if (self.data.curType == 1) {
            chain = 'id|' + self.data.storeChainInfo[self.data.storeDistanceMinIndex].chain_id + ',';
            chain += 'buyer_name|' + self.data.username + ',';
            chain += 'mob_phone|' + self.data.chain_member_phone;
        }
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=order_pay',
            data: {
                key: self.data.key,
                ifcart: self.data.ifcart,
                cart_id: self.data.cart_id,
                address_id: self.data.address_id,
                arrival: self.data.arrival,
                invoice_id: self.data.invoice_id,
                pintuan: '',
                log_id: '',
                buyer_id: '',
                vat_hash: self.data.vat_hash,
                pay_name: self.data.pay_name,
                offpay_hash: self.data.address_api.offpay_hash,
                offpay_hash_batch: self.data.address_api.offpay_hash_batch,
                pay_message: self.data.leaveMsg,
                pd_pay: self.data.pd_pay,
                // fcode: fcode,
                rcb_pay: self.data.rcb_pay,
                rpt: self.data.rpt,
                voucher: self.data.voucher,
                buy_type: 'wechat',
                chain: chain,
                // chain: {
                //     id: '12',
                //     buyer_name: self.data.address_info.true_name,
                //     mob_phone: self.data.address_info.mob_phone
                // },

            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            dataType: 'json',
            success: (res) => {
                if (res.data.code != 200) {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none'
                    })
                } else {
                    self.setData({
                        pay_info: res.data.datas.pay_info,
                        wechat_paynum: '￥' + res.data.datas.pay_info.pay_amount
                    })
                    this.util1('open')
                }
            }
        })
    },
    getParam: function (address_api) {
        var delFee = {};
        if (address_api.content) {
            for (var i in address_api.content) {
                delFee[i] = parseFloat(address_api.content[i]).toFixed(2);
            }
            this.setData({
                delFee: delFee,
            })
        } else {
            for (let k in this.data.store_cart_list) {
                delFee[k] = 5.00
            }
            this.setData({
                delFee: delFee,
            })
        }
        var storeGoodsTotal = 0;
        var delFeeTotal = 0;
        var totalPrice = 0;
        for (let k in this.data.store_cart_list) {
            storeGoodsTotal += this.data.store_cart_list[k].store_goods_total * 1;
        }
        for (let k in delFee) {
            delFeeTotal += delFee[k] * 1;
        }
        totalPrice = (storeGoodsTotal + delFeeTotal).toFixed(2);
        this.setData({
            totalPrice: totalPrice,
            totalPriceTmpl: totalPrice,
            inittotalPrice: totalPrice
        })
        if (JSON.stringify(this.data.storeVoucher) != "{}") {
            for (let key in this.data.storeVoucher) {
                if (this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].limit != 0) {
                    this.data.totalPrice -= this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_price
                }
            }
            this.setData({
                totalPrice: (this.data.totalPrice * 1).toFixed(2),
                inittotalPrice: this.data.totalPrice
            })
            for (let key in this.data.storeVoucher) {
                if (this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].limit != 0) {
                    this.data.voucher += (this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_t_id + '|' + key + '|' + this.data.store_cart_list[key].store_voucher_list[this.data.storeVoucher[key]].voucher_price) + ','
                }
            }
        }

    },
    invoiceSelect: function () {
        wx.navigateTo({
            url: '../invoice/invoice'
        })
    },
    leaveMsg: function (e) {
        leaveMsg[e.target.dataset.storeid] = e.detail.value;
        var msg = '';
        for (var k in leaveMsg) {
            msg += k + '|' + leaveMsg[k] + ',';
        }
        this.setData({
            leaveMsg: msg
        })
    },
    payPsw: function (e) {
        if (this.data.rcb_pay == 1 || this.data.pd_pay == 1) {
            this.setData({
                payPsw: e.detail.value
            })
        } else {
            this.setData({
                payPsw: ''
            })
        }
    },
    chainMemberPhone: function (e) {
        this.setData({
            chain_member_phone: e.detail.value
        })
    },
    orderUp: function (e) {
        var currentStatu = e.currentTarget.dataset.statu;
        this.util1(currentStatu)
    },
    util1: function (currentStatu) {
        var self = this;
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear',
            delay: 0,
        });
        this.animation = animation;
        animation.translateY(400).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation
            })
            if (currentStatu == "close") {
                this.setData({
                    showModalStatus1: false,
                    rcbState: false,
                    pdState: false,
                    showRercb: false,
                    showRepd: false,
                    rcb_pay: 0,
                    pd_pay: 0,
                    wechatpaySelected: true
                });
            }
        }.bind(this), 200)
        if (currentStatu == "open") {
            this.setData({
                showModalStatus1: true
            });
        }
    },
    selectRcb: function (e) {
        var rcbValue = e.target.dataset.rcb;
        var state = e.detail.value;
        var pay_info = this.data.pay_info;
        this.setData({
            rcbState: state,
            showRercb: !this.data.showRercb
        })
        if (state) {
            this.data.rcb_pay = 1
        } else {
            this.data.rcb_pay = 0
        }
        //预存款处于关闭状态
        if (!this.data.pdState) {
            //充值卡金额大于支付金额
            if (rcbValue - pay_info.pay_amount >= 0 && state) {
                this.setData({
                    rercbNum: pay_info.pay_amount,
                    wechat_paynum: ''
                })
            } else if (rcbValue - pay_info.pay_amount < 0 && (pay_info.pay_amount - rcbValue) <= pay_info.member_available_pd && state) {
                this.setData({
                    rercbNum: pay_info.member_available_rcb,
                    wechat_paynum: '￥' + (pay_info.pay_amount - pay_info.member_available_rcb).toFixed(2)
                })
            } else if (!state) {
                this.setData({
                    wechat_paynum: '￥' + pay_info.pay_amount
                })
            } else {
                this.setData({
                    rercbNum: pay_info.member_available_rcb,
                    wechat_paynum: '￥' + (pay_info.pay_amount - pay_info.member_available_rcb).toFixed(2)
                })
            }
        } else {
            //预存款处于开启状态
            if (pay_info.member_available_pd - pay_info.pay_amount > 0 && state) {
                if (rcbValue - pay_info.pay_amount > 0) {
                    this.setData({
                        pdState: false,
                        showRepd: false,
                        rercbNum: pay_info.pay_amount,
                        wechat_paynum: ''
                    })
                } else {
                    this.setData({
                        pdState: false,
                        showRepd: false,
                        rercbNum: rcbValue,
                        wechat_paynum: '￥' + (pay_info.pay_amount - rcbValue).toFixed(2)
                    })
                }
            } else if (pay_info.member_available_pd - pay_info.pay_amount < 0 && state) {
                if (rcbValue - pay_info.pay_amount >= 0) {
                    this.setData({
                        pdState: false,
                        showRepd: false,
                        rercbNum: pay_info.pay_amount,
                        wechat_paynum: '',
                    })
                } else {
                    this.setData({
                        pdState: false,
                        showRepd: false,
                        rercbNum: pay_info.member_available_rcb,
                        wechat_paynum: '￥' + (pay_info.pay_amount - rcbValue).toFixed(2)
                    })
                }
            } else if (pay_info.pay_amount - rcbValue > pay_info.member_available_pd) {
                this.setData({
                    wechat_paynum: '￥' + (pay_info.pay_amount - pay_info.member_available_pd).toFixed(2)
                })
            }
        }
        if (this.data.wechat_paynum == '') {
            this.setData({
                wechatpaySelected: false
            })
        } else {
            this.setData({
                wechatpaySelected: true
            })
        }
    },
    selectPd: function (e) {
        var pdValue = e.target.dataset.pd;
        var state = e.detail.value;
        var pay_info = this.data.pay_info;
        var rcbValue = pay_info.member_available_rcb;
        this.setData({
            pdState: state,
            showRepd: !this.data.showRepd
        })
        if (state) {
            this.data.pd_pay = 1
        } else {
            this.data.pd_pay = 0
        }
        //充值卡处于关闭状态
        if (!this.data.rcbState) {
            //预存款金额大于支付金额
            if (pdValue - pay_info.pay_amount >= 0 && state) {
                if (rcbValue - pay_info.pay_amount >= 0) {
                    this.setData({
                        repdNum: pay_info.pay_amount,
                        // disableRcp: true,
                        wechat_paynum: ''
                    })
                } else {
                    this.setData({
                        repdNum: pay_info.pay_amount,
                        disableRcp: true,
                        wechat_paynum: ''
                    })
                }

            } else if (pdValue - pay_info.pay_amount < 0 && state) {
                this.setData({
                    repdNum: pdValue,
                    wechat_paynum: '￥' + (pay_info.pay_amount - pdValue).toFixed(2)
                })
            } else if (!state) {
                this.setData({
                    disableRcp: false,
                    wechat_paynum: '￥' + pay_info.pay_amount
                })
            }
        } else {
            //充值卡处于开启状态
            //预存款金额大于支付金额
            if (rcbValue - pay_info.pay_amount >= 0 && state) {
                if (pdValue - pay_info.pay_amount >= 0) {
                    this.setData({
                        rcbState: false,
                        showRercb: false,
                        repdNum: pay_info.pay_amount,
                        wechat_paynum: ''
                    })
                } else {
                    this.setData({
                        rcbState: false,
                        showRercb: false,
                        // disableRcp: true,
                        repdNum: pay_info.member_available_pd,
                        wechat_paynum: '￥' + (pay_info.pay_amount - pdValue).toFixed(2)
                    })
                }
            } else if (rcbValue - pay_info.pay_amount < 0 && (pay_info.pay_amount - rcbValue) <= pay_info.member_available_pd && state) {
                //支付金额大于充值卡金额小于充值卡预存款之和
                this.setData({
                    repdNum: (pay_info.pay_amount - rcbValue).toFixed(2),
                    disableRcp: true,
                    wechat_paynum: ''
                })
            } else if (pay_info.pay_amount - rcbValue > pay_info.member_available_pd) {
                if (state) {
                    this.setData({
                        wechat_paynum: '￥' + (pay_info.pay_amount - rcbValue - pay_info.member_available_pd).toFixed(2),
                        repdNum: pay_info.member_available_pd
                    })
                } else {
                    this.setData({
                        wechat_paynum: '￥' + (pay_info.pay_amount - rcbValue).toFixed(2)
                    })
                }
            } else if (!state) {
                this.setData({
                    disableRcp: false,
                    wechat_paynum: '￥' + (pay_info.pay_amount - rcbValue).toFixed(2)
                })
            } else {
                this.setData({
                    repdNum: pay_info.member_available_pd
                })
            }
        }
        if (this.data.wechat_paynum == '') {
            this.setData({
                wechatpaySelected: false
            })
        } else {
            this.setData({
                wechatpaySelected: true
            })
        }
    },
    confirmPay: function () {
        if (!this.data.showConfirmPay) {
            return;
        }
        this.setData({
            showConfirmPay: false
        })
        var self = this;
        var password;
        if (this.data.pd_pay == 1 || this.data.rcb_pay == 1) {
            password = self.data.payPsw;
        } else {
            password = '';
        }
        var chain = ''
        if (this.data.curType == 1) {
            chain = 'id|' + self.data.storeChainInfo[self.data.storeDistanceMinIndex].chain_id + ',';
            chain += 'buyer_name|' + self.data.username + ',';
            chain += 'mob_phone|' + self.data.chain_member_phone;
        }
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=buy_step2',
            dataType: 'json',
            method: 'POST',
            data: {
                key: self.data.key,
                ifcart: self.data.ifcart,
                cart_id: self.data.cart_id,
                address_id: self.data.address_id,
                pintuan: '',
                log_id: '',
                buyer_id: '',
                vat_hash: self.data.vat_hash,
                offpay_hash: self.data.address_api.offpay_hash,
                offpay_hash_batch: self.data.address_api.offpay_hash_batch,
                pay_name: self.data.pay_name,
                invoice_id: self.data.invoice_id,
                pd_pay: self.data.pd_pay,
                // fcode: fcode,
                rcb_pay: self.data.rcb_pay,
                rpt: self.data.rpt,
                voucher: self.data.voucher,
                arrival: self.data.arrival,
                pay_message: self.data.leaveMsg,
                password: password,
                order_from: 5,
                chain: chain,
                buy_type: 'wechat'
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: (resb) => {
                if (resb.data.code == 200) {
                    var pay_sn = resb.data.datas.pay_sn;
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_payment&op=wechat_pay',
                        data: {
                            key: self.data.key,
                            pay_sn: pay_sn,
                            rcb_pay: self.data.rcb_pay,
                            pd_pay: self.data.pd_pay,
                            payment_code: 'wxpay'
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: (res) => {
                            if (res.data.code != 200) {
                                wx.showToast({
                                    title: res.data.datas.error,
                                    icon: 'none'
                                })
                            } else {
                                if (res.data.datas.pay_code == 'available') {
                                    self.setData({
                                        showConfirmPay: true
                                    })
                                    self.changeCart(self.data.ifcart, self.data.cart_id);
                                    wx.redirectTo({
                                        url: '../myOrder/myOrder?state_type=state_send'
                                    })
                                } else {
                                    let api_pay_amount;
                                    let account = self.data.pay_info
                                    if (self.data.rcb_pay == 1 && self.data.pd_pay == 0) {
                                        api_pay_amount = account.pay_amount - account.member_available_rcb
                                    }
                                    if (self.data.rcb_pay == 0 && self.data.pd_pay == 1) {
                                        api_pay_amount = account.pay_amount - account.member_available_pd
                                    }
                                    if (self.data.rcb_pay == 1 && self.data.pd_pay == 1) {
                                        api_pay_amount = account.pay_amount - account.member_available_rcb - account.member_available_pd
                                    }
                                    if (self.data.rcb_pay == 0 && self.data.pd_pay == 0) {
                                        api_pay_amount = account.pay_amount
                                    }
                                    wx.request({
                                        url: app.globalData.ApiUrl + '/index.php?act=member_payment&op=pay_new_mini',
                                        method: 'GET',
                                        data: {
                                            key: self.data.key,
                                            open_id: self.data.openid,
                                            pay_sn: pay_sn,
                                            api_pay_amount: api_pay_amount
                                        },
                                        success: payres => {
                                            wx.requestPayment({
                                                timeStamp: payres.data.timeStamp,
                                                nonceStr: payres.data.nonceStr,
                                                package: payres.data.package,
                                                signType: 'MD5',
                                                paySign: payres.data.paySign,
                                                success(resa) {
                                                    self.setData({
                                                        showConfirmPay: true
                                                    })
                                                    self.changeCart(self.data.ifcart, self.data.cart_id);
                                                    wx.redirectTo({
                                                        url: '../myOrder/myOrder?state_type=state_send'
                                                    })
                                                },
                                                fail(res) {
                                                    self.setData({
                                                        showConfirmPay: true
                                                    })
                                                    self.changeCart(self.data.ifcart, self.data.cart_id);
                                                    if (res.errMsg == "requestPayment:fail cancel") {
                                                        wx.redirectTo({
                                                            url: '../myOrder/myOrder?state_type=state_new'
                                                        })
                                                    }
                                                }
                                            })
                                        }
                                    })
                                }
                            }
                        },
                    });

                } else {
                    self.setData({
                        showConfirmPay: true
                    })
                    self.changeCart(self.data.ifcart, self.data.cart_id);
                    wx.showToast({
                        title: resb.data.datas.error,
                        icon: 'none'
                    })
                }
            }
        })
    },

    changeCart: function (ifcart, cart_id) {
        if (ifcart == 1) {
            let cart_str = cart_id.substring(0, cart_id.lastIndexOf(','));
            let cart = cart_str.split(',');
            let quantity = 0;
            for (var i in cart) {
                var each_cart = cart[i].split('|');
                quantity += parseInt(each_cart[1]);
            }
            wx.getStorage({
                key: 'cart_count',
                success: (res) => {
                    wx.setTabBarBadge({
                        index: 3,
                        text: String(res.data - quantity)
                    })
                    wx.setStorage({
                        key: 'cart_count',
                        data: res.data - quantity
                    })
                }
            })

        }
    },
    orderClose: function () {
        var self = this;
        var chain = ''
        if (self.data.curType == 1) {
            chain = 'id|' + self.data.storeChainInfo[self.data.storeDistanceMinIndex].chain_id + ',';
            chain += 'buyer_name|' + self.data.username + ',';
            chain += 'mob_phone|' + self.data.chain_member_phone;
        }
        wx.showModal({
            title: '确认要离开支付？',
            content: '您的订单在1小时内未支付将被取消，请尽快完成支付。',
            success(res) {
                if (res.confirm) {
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=buy_step2',
                        dataType: 'json',
                        method: 'POST',
                        data: {
                            key: self.data.key,
                            ifcart: self.data.ifcart,
                            cart_id: self.data.cart_id,
                            address_id: self.data.address_id,
                            pintuan: '',
                            log_id: '',
                            buyer_id: '',
                            vat_hash: self.data.vat_hash,
                            offpay_hash: self.data.address_api.offpay_hash,
                            offpay_hash_batch: self.data.address_api.offpay_hash_batch,
                            pay_name: self.data.pay_name,
                            invoice_id: self.data.invoice_id,
                            // voucher: voucher_temp,
                            pd_pay: self.data.pd_pay,
                            // fcode: fcode,
                            rcb_pay: self.data.rcb_pay,
                            // rpt: rpt_temp,
                            arrival: self.data.arrival,
                            pay_message: self.data.leaveMsg,
                            password: '',
                            order_from: 5,
                            chain: chain,
                            buy_type: 'wechat'
                        },
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        success: (resb) => {
                            if (resb.data.code == 200) {
                                wx.redirectTo({
                                    url: '../myOrder/myOrder?state_type=state_new'
                                })
                            } else {
                                wx.showToast({
                                    title: resb.data.datas.error,
                                    icon: 'none'
                                })
                            }
                        }
                    })


                }
            }
        })
    },
    changeCurType: function (e) {
        this.setData({
            rptIndex: '',
            voucher: '',
            rpt: ''
        })
        let type = e.currentTarget.dataset.type;
        this.setData({
            curType: type
        })
        var self = this;
        var ifchain = '';
        if (type == 1) {
            ifchain = '1'
        }
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_buy&op=buy_step1',
            data: {
                key: self.data.key,
                cart_id: self.data.cart_id,
                ifcart: self.data.ifcart,
                address_id: self.data.address_id,
                pintuan: '',
                ifchain: ifchain,
                chain_id: ''
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            dataType: 'json',
            success: (res) => {
                if (res.data.code == 200) {
                    for (let k in res.data.datas.store_cart_list) {
                        if (res.data.datas.store_cart_list[k].store_voucher_list.length > 0) {
                            self.data.storeVoucher[k] = 0
                        }
                    }
                    self.setData({
                        address_info: res.data.datas.address_info,
                        store_cart_list: res.data.datas.store_cart_list,
                        address_id: res.data.datas.address_info.address_id,
                        vat_hash: res.data.datas.vat_hash,
                        address_api: res.data.datas.address_api,
                        invoice_cont: res.data.datas.inv_info.content,
                        rpt_list: res.data.datas.rpt_list,
                        storeVoucher: self.data.storeVoucher,
                        storeChainInfo: res.data.datas.store_chain_list
                    })
                    wx.getStorage({
                        key: 'latitude',
                        success: res => {
                            let latitude = res.data
                            wx.getStorage({
                                key: 'longitude',
                                success: resl => {
                                    let longitude = resl.data;
                                    var locationArray = [];
                                    for (let i = 0; i < self.data.storeChainInfo.length; i++) {
                                        locationArray[i] = self.data.storeChainInfo[i].location
                                    }
                                    //获取距离店铺位置
                                    qqmapsdk.calculateDistance({
                                        mode: 'walking',
                                        from: {
                                            latitude: latitude,
                                            longitude: longitude
                                        },
                                        to: locationArray,
                                        success: ressuc => {
                                            if (ressuc.result.elements.length == 1) {
                                                self.setData({
                                                    storeDistanceMinIndex: 0
                                                })
                                            } else {
                                                let minDistance = Math.min.apply(Math, ressuc.result.elements.map(item => {
                                                    return item.distance;
                                                }))
                                                for (let i = 0; i < ressuc.result.elements.length; i++) {
                                                    if (ressuc.result.elements[i].distance == minDistance) {
                                                        self.setData({
                                                            storeDistanceMinIndex: i
                                                        })
                                                    }
                                                }
                                            }
                                            self.setData({
                                                storeDistance: ressuc.result.elements
                                            })
                                        }
                                    })
                                }
                            })
                        }
                    })
                    if (JSON.stringify(res.data.datas.address_info) == "{}") {
                        wx.showModal({
                            title: '温馨提示',
                            content: '请添加收货人信息',
                            success: res => {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '../address_choose/address_choose?iforder=1'
                                    })
                                } else if (res.cancel) {
                                    wx.switchTab({
                                        url: '../cart/cart'
                                    })
                                }
                            }
                        })
                    }
                    if (res.data.datas.inv_info.content == '不需要发票') {
                        self.setData({
                            invoice_id: 0,
                        })
                    } else {
                        self.setData({
                            invoice_id: res.data.datas.inv_info.inv_id
                        })
                    }
                    var arrival = '';
                    var arrivalTime = {};
                    for (var i in res.data.datas.store_cart_list) {
                        arrivalTime['store_id' + i] = res.data.datas.store_cart_list[i].max_time_reach;
                        arrival += 'store_id' + i + '|' + res.data.datas.store_cart_list[i].max_time_reach + ',';
                    }
                    self.setData({
                        arrivalObj: arrivalTime,
                        arrival: arrival
                    })
                    this.getParam(res.data.datas.address_api)
                } else {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none',
                        success: () => {
                            setTimeout(function () {
                                wx.switchTab({
                                    url: '../cart/cart'
                                })
                            }, 1500)
                        }
                    })

                }
            }
        });
    },
    checkMap: function () {
        let storeChainInfo = this.data.storeChainInfo;
        let storeDistanceMinIndex = this.data.storeDistanceMinIndex;
        wx.openLocation({
            latitude: storeChainInfo[storeDistanceMinIndex].location.latitude,
            longitude: storeChainInfo[storeDistanceMinIndex].location.longitude,
            name: storeChainInfo[storeDistanceMinIndex].chain_address
        })
    },
    confirmGetStore: function (e) {
        var self = this;
        var currentStatu = e.currentTarget.dataset.statu;
        var index = e.currentTarget.dataset.index;
        this.setData({
            storeDistanceMinIndex: index
        })
        setTimeout(function () {
            self.utilStore(currentStatu)
        }, 200)
    },
    checkPatMap: function (e) {
        let index = e.currentTarget.dataset.index;
        let location = this.data.storeChainInfo[index].location
        wx.openLocation({
            latitude: location.latitude,
            longitude: location.longitude,
            name: this.data.storeChainInfo[index].chain_address
        })
    },
    onShareAppMessage: function () {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        }
    }
})